<template>
  <div id="addQuestionView">
    <h2>创建题解</h2>
    <a-form :model="form" label-align="left">
      <a-form-item field="title" label="标题">
        <a-input v-model="form.title" placeholder="请输入标题" />
      </a-form-item>
      <a-form-item field="content" label="内容">
        <a-textarea v-model="form.content" style="height: 140px;"></a-textarea>
      </a-form-item>
      <a-form-item field="code" label="代码">
        <a-textarea v-model="form.code" style="height: 200px;"></a-textarea>
      </a-form-item>
      <a-form-item>
        <a-space>
          <a-button type="primary" style="min-width: 200px" @click="doSubmit">提交
          </a-button>
          <a-button type="primary" style="min-width: 200px" @click="toBackView">返回
          </a-button>
        </a-space>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { onBeforeMount, onMounted, ref } from "vue";
import MdEditor from "@/components/MdEditor.vue";
import { QuestionControllerService, CommonControllerService, QuestionAnswerControllerService } from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import { useRoute, useRouter } from "vue-router";

const route = useRoute();
// 如果页面地址包含 update，视为更新页面
const updatePage = route.path.includes("update");

let form = ref({
  id: undefined,
  questionId: undefined,
  title: "",
  content: "",
  code: "",
});

interface Props {
  id: number;//题目id,
}

const props = withDefaults(defineProps<Props>(), {
  id: undefined,
});

/**
 * 根据题目 id 获取老的数据
 */
const loadData = async () => {

  form.value.questionId = props.id
  if(updatePage){
    const res = await QuestionAnswerControllerService.getAnswerVoByIdUsingGet(
      props.id as any
    );
    form.value = res.data
  }
  
};

onMounted(() => {
  loadData();
});

const doSubmit = async () => {
  // 区分更新还是创建
  const res = await QuestionAnswerControllerService.addAnswerUsingPost(
    form.value,
  )
  if (res.code === 0) {
      message.success("更新成功");
    } else {
      message.error("更新失败，" + res.message);
    }
  toHomeView();
};

const router = useRouter();

const toHomeView = () => {
  router.push({
    path: `/`,
  });
};

const toBackView = () => {
  router.back();
}


</script>

<style scoped>
#addQuestionView {}
</style>
